package com.company.dcm.config;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaHttpMethod;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import com.company.dcm.common.JacksonObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.*;

import java.util.List;

@Slf4j
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册 Sa-Token 拦截器，定义详细认证规则
        registry.addInterceptor(new SaInterceptor(handler -> {

            //解决拦截器中对预检请求进行登录校验，直接放行
            SaRouter.match(SaHttpMethod.OPTIONS)
                    .notMatch("/login","/logout","/register","/api/**")
                    //.free(r -> System.out.println("--------OPTIONS预检请求，不做处理--------"))
                    .back(SaHolder.getResponse()
                            .setHeader("Access-Control-Allow-Origin", "*")
                            .setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, PATCH, OPTIONS, HEAD")
                            .setHeader("Access-Control-Max-Age", "3600")
                            .setHeader("Access-Control-Allow-Headers", "Authorization,DNT,Accept,Origin,Keep-Alive,User-Agent,X-Mx-ReqToken,X-Data-Type,X-Auth-Token,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Referer"));//如设置为*，会每次都预检

            SaRouter.match(SaHttpMethod.OPTIONS)
                    .match("/login","/logout","/register","/api/**")
                    //.free(r -> System.out.println("--------OPTIONS预检请求，不做处理--------"))
                    .back(SaHolder.getResponse()
                            .setHeader("Access-Control-Allow-Origin", "*")
                            .setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, PATCH, OPTIONS, HEAD")
                            .setHeader("Access-Control-Max-Age", "3600")
                            .setHeader("Access-Control-Allow-Headers", "*"));//设置为*不会要求具体字段，设置具体字段如果对方没有，请求会报错

            // 指定一条 match 规则
            SaRouter.match("/**")
                    .notMatch("/MES/download","/MES/download/**",
                            "/ClothSheetFourScore/download/R_ClothSheetDetailFourScore",
                            "/login","/logout","/register","/dev/getDev","/MES/remote/get/equipmentNum/list","/OTA/subscribe","/OTA/updateOTA","/OTA/updateAllOTA",
                            "/api/**")
                    .check(r -> StpUtil.checkLogin());

        })).addPathPatterns("/**").excludePathPatterns("/favicon.ico");
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 设置允许跨域的路径
        registry.addMapping("/**")
                // 设置允许跨域请求的域名
                .allowedOriginPatterns("*")
                // 是否允许cookie
                .allowCredentials(true)
                // 设置允许的请求方式
                .allowedMethods("GET", "POST", "DELETE", "PUT","PATCH","OPTIONS","HEAD")
                // 设置允许的header属性
                .allowedHeaders("DNT,Authorization,Accept,Origin,Keep-Alive,User-Agent,X-Mx-ReqToken,X-Data-Type,X-Auth-Token,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Referer")
                // 跨域允许时间
                .maxAge(3600);
    }

    /**
     * 扩展mvc框架的消息转换器
     * @param converters
     */
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        log.info("扩展消息转换器...");
        //创建消息转换器对象
        MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
        //设置对象转换器，底层使用Jackson将Java对象转为json
        messageConverter.setObjectMapper(new JacksonObjectMapper());
        //将上面的消息转换器对象追加到mvc框架的转换器集合中
        converters.add(0,messageConverter);
    }

}
